#!/usr/bin/python3
"""
OpenCloudOS 9 AI软件自动化验证工具 - 高级命令行接口
"""

import argparse
import json
import sys
from pathlib import Path
from datetime import datetime
import webbrowser
from ai_package_validator import AIPackageValidator


class AdvancedCLI:
    """高级命令行接口"""
    
    def __init__(self):
        self.validator = AIPackageValidator()
        
    def load_config(self, config_file: str) -> dict:
        """加载配置文件"""
        try:
            with open(config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
            return config
        except Exception as e:
            print(f"❌ 加载配置文件失败: {e}")
            sys.exit(1)
    
    def validate_single_package(self, package_name: str, version: str = None, 
                              tests_file: str = None) -> dict:
        """验证单个包"""
        print(f"🔍 开始验证包: {package_name}")
        
        # 构建包配置
        package_config = {
            "name": package_name,
            "version": version,
            "custom_tests": []
        }
        
        # 如果提供了测试文件，加载自定义测试
        if tests_file and Path(tests_file).exists():
            try:
                with open(tests_file, 'r', encoding='utf-8') as f:
                    tests_config = json.load(f)
                    package_config["custom_tests"] = tests_config.get("custom_tests", [])
            except Exception as e:
                print(f"⚠️  加载测试文件失败: {e}")
        
        result = self.validator.validate_package(package_config)
        return result
    
    def validate_batch(self, config_file: str, filter_packages: list = None, parallel: bool = False) -> dict:
        """批量验证"""
        config = self.load_config(config_file)
        packages = config.get("packages", [])
        
        # 过滤包
        if filter_packages:
            packages = [pkg for pkg in packages if pkg["name"] in filter_packages]
            print(f"🔍 筛选后验证 {len(packages)} 个包: {', '.join(filter_packages)}")
        else:
            print(f"🔍 开始批量验证 {len(packages)} 个包")
        
        result = self.validator.batch_validate(packages, parallel)
        return result
    
    def list_packages(self, config_file: str):
        """列出配置文件中的包"""
        config = self.load_config(config_file)
        packages = config.get("packages", [])
        
        print(f"\n📦 配置文件中的包列表 ({len(packages)} 个):")
        print("-" * 80)
        for i, pkg in enumerate(packages, 1):
            name = pkg.get("name", "Unknown")
            version = pkg.get("version", "latest")
            description = pkg.get("description", "")
            custom_tests_count = len(pkg.get("custom_tests", []))
            
            print(f"{i:2d}. {name:20s} (v{version:8s}) - {description}")
            print(f"    └─ 自定义测试: {custom_tests_count} 个")
        print("-" * 80)
    
    def generate_report(self, log_dir: str = "validation_logs", format: str = "text"):
        """生成验证报告"""
        log_path = Path(log_dir)
        if not log_path.exists():
            print(f"❌ 日志目录不存在: {log_dir}")
            return
        
        # 查找最新的批量验证日志
        batch_logs = list(log_path.glob("batch_validation_*.json"))
        if not batch_logs:
            print(f"❌ 未找到批量验证日志文件")
            return
        
        latest_log = max(batch_logs, key=lambda x: x.stat().st_mtime)
        
        try:
            with open(latest_log, 'r', encoding='utf-8') as f:
                batch_result = json.load(f)
            
            if format == "html":
                self._generate_html_report(batch_result, log_dir)
            else:
                self._print_detailed_report(batch_result)
            
        except Exception as e:
            print(f"❌ 生成报告失败: {e}")
    
    def _generate_html_report(self, batch_result: dict, log_dir: str):
        """生成HTML格式的验证报告"""
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        html_file = Path(log_dir) / f"validation_report_{timestamp}.html"
        
        # 生成HTML内容
        html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OpenCloudOS 9 AI软件包验证报告</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }}
        .container {{ max-width: 1200px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
        h1, h2 {{ color: #333; }}
        .summary {{ background-color: #e9f7ef; padding: 15px; border-radius: 5px; margin-bottom: 20px; }}
        .summary.error {{ background-color: #fceaea; }}
        .summary.warning {{ background-color: #fff8e1; }}
        .package-list {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 15px; }}
        .package-card {{ border: 1px solid #ddd; border-radius: 5px; padding: 15px; }}
        .package-card.success {{ border-left: 5px solid #4caf50; }}
        .package-card.failure {{ border-left: 5px solid #f44336; }}
        .status-icon {{ font-size: 24px; margin-right: 10px; }}
        .success {{ color: #4caf50; }}
        .failure {{ color: #f44336; }}
        .warning {{ color: #ff9800; }}
        table {{ width: 100%; border-collapse: collapse; margin: 20px 0; }}
        th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
        th {{ background-color: #f2f2f2; }}
        .chart-container {{ height: 300px; margin: 30px 0; }}
    </style>
</head>
<body>
    <div class="container">
        <h1>🏥 OpenCloudOS 9 AI软件包验证报告</h1>
        
        <div class="summary">
            <h2>📊 概要信息</h2>
            <p><strong>验证时间:</strong> {batch_result.get('batch_timestamp', 'Unknown')}</p>
            <p><strong>总包数量:</strong> {batch_result.get('total_packages', 0)}</p>
            <p><strong>成功包数:</strong> {batch_result.get('successful_packages', 0)}</p>
            <p><strong>失败包数:</strong> {batch_result.get('failed_packages', 0)}</p>
            <p><strong>成功率:</strong> {batch_result.get('summary', {}).get('success_rate', 0):.1f}%</p>
        </div>
        
        <h2>📋 详细结果</h2>
        <div class="package-list">
"""

        # 添加成功和失败的包信息
        successful_packages = []
        failed_packages = []
        
        for result in batch_result.get('packages_results', []):
            package_name = result.get('package', 'Unknown')
            if result.get('overall_success', False):
                successful_packages.append((package_name, result))
            else:
                failed_packages.append((package_name, result))
        
        # 成功的包
        for pkg_name, result in successful_packages:
            html_content += f"""
            <div class="package-card success">
                <h3><span class="status-icon">✅</span> {pkg_name}</h3>
                <p><strong>状态:</strong> <span class="success">成功</span></p>
                <p><strong>版本:</strong> {result.get('package_info', {}).get('version', 'Unknown')}</p>
            </div>
"""
        
        # 失败的包
        for pkg_name, result in failed_packages:
            html_content += f"""
            <div class="package-card failure">
                <h3><span class="status-icon">❌</span> {pkg_name}</h3>
                <p><strong>状态:</strong> <span class="failure">失败</span></p>
"""
            
            # 显示失败原因
            if not result.get('install_result', {}).get('install_success', True):
                install_error = result.get('install_result', {}).get('error_message', '')
                html_content += f"                <p><strong>安装失败:</strong> {install_error}</p>\n"
            
            # 显示测试失败详情
            failed_tests = [test for test in result.get('tests', []) if not test.get('success', True)]
            if failed_tests:
                html_content += "                <p><strong>测试失败:</strong></p>\n                <ul>\n"
                for test in failed_tests:
                    test_name = test.get('test_name', test.get('test_type', 'Unknown'))
                    error_msg = test.get('error_message', '')[:100] + '...' if len(test.get('error_message', '')) > 100 else test.get('error_message', '')
                    html_content += f"                    <li>{test_name}: {error_msg}</li>\n"
                html_content += "                </ul>\n"
            
            html_content += "            </div>\n"
        
        html_content += """
        </div>
        
        <h2>💡 建议</h2>
"""
        
        success_rate = batch_result.get('summary', {}).get('success_rate', 0)
        if success_rate >= 90:
            html_content += """
        <div class="summary">
            <p>🎉 验证结果优秀！大部分AI软件包在OpenCloudOS 9上运行良好。</p>
        </div>
"""
        elif success_rate >= 70:
            html_content += """
        <div class="summary warning">
            <p>⚠️ 验证结果良好，但还有改进空间。建议关注失败的包。</p>
        </div>
"""
        else:
            html_content += """
        <div class="summary error">
            <p>🚨 验证结果需要改进。建议检查环境配置和依赖问题。</p>
        </div>
"""
        
        if failed_packages:
            html_content += """
        <div>
            <p><strong>对于失败的包，建议:</strong></p>
            <ul>
                <li>检查系统依赖是否完整</li>
                <li>确认Python版本兼容性</li>
                <li>查看详细错误日志</li>
                <li>考虑使用不同版本</li>
            </ul>
        </div>
"""
        
        html_content += """
    </div>
</body>
</html>
"""
        
        # 保存HTML文件
        with open(html_file, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        print(f"✅ HTML报告已生成: {html_file}")
        print(f"🌐 在浏览器中打开报告: file://{html_file.absolute()}")
    
    def _print_detailed_report(self, batch_result: dict):
        """打印详细报告"""
        print(f"\n" + "="*80)
        print(f"🏥 OpenCloudOS 9 AI软件包验证报告")
        print(f"="*80)
        
        # 基本信息
        print(f"验证时间: {batch_result.get('batch_timestamp', 'Unknown')}")
        print(f"总包数量: {batch_result.get('total_packages', 0)}")
        print(f"成功包数: {batch_result.get('successful_packages', 0)}")
        print(f"失败包数: {batch_result.get('failed_packages', 0)}")
        
        success_rate = batch_result.get('summary', {}).get('success_rate', 0)
        print(f"成功率: {success_rate:.1f}%")
        
        # 成功/失败状态图标
        if success_rate >= 90:
            status_icon = "🟢"
        elif success_rate >= 70:
            status_icon = "🟡"
        else:
            status_icon = "🔴"
        
        print(f"总体状态: {status_icon}")
        
        print(f"\n" + "-"*80)
        print(f"📋 详细结果")
        print(f"-"*80)
        
        # 分类显示结果
        successful_packages = []
        failed_packages = []
        
        for result in batch_result.get('packages_results', []):
            package_name = result.get('package', 'Unknown')
            if result.get('overall_success', False):
                successful_packages.append(package_name)
            else:
                failed_packages.append((package_name, result))
        
        # 成功的包
        if successful_packages:
            print(f"\n✅ 成功的包 ({len(successful_packages)}):")
            for i, pkg in enumerate(successful_packages, 1):
                print(f"  {i:2d}. {pkg}")
        
        # 失败的包
        if failed_packages:
            print(f"\n❌ 失败的包 ({len(failed_packages)}):")
            for i, (pkg, result) in enumerate(failed_packages, 1):
                print(f"  {i:2d}. {pkg}")
                
                # 显示失败原因
                if not result.get('install_result', {}).get('install_success', True):
                    install_error = result.get('install_result', {}).get('error_message', '')
                    print(f"      └─ 安装失败: {install_error}")
                
                # 显示测试失败详情
                failed_tests = [test for test in result.get('tests', []) if not test.get('success', True)]
                if failed_tests:
                    print(f"      └─ 测试失败:")
                    for test in failed_tests:
                        test_name = test.get('test_name', test.get('test_type', 'Unknown'))
                        error_msg = test.get('error_message', '')[:60] + '...' if len(test.get('error_message', '')) > 60 else test.get('error_message', '')
                        print(f"         • {test_name}: {error_msg}")
        
        print(f"\n" + "="*80)
        print(f"📊 建议")
        print(f"="*80)
        
        if success_rate >= 90:
            print("🎉 验证结果优秀！大部分AI软件包在OpenCloudOS 9上运行良好。")
        elif success_rate >= 70:
            print("⚠️  验证结果良好，但还有改进空间。建议关注失败的包。")
        else:
            print("🚨 验证结果需要改进。建议检查环境配置和依赖问题。")
        
        if failed_packages:
            print(f"\n💡 对于失败的包，建议:")
            print(f"   1. 检查系统依赖是否完整")
            print(f"   2. 确认Python版本兼容性")
            print(f"   3. 查看详细错误日志")
            print(f"   4. 考虑使用不同版本")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(
        description="OpenCloudOS 9 AI软件自动化验证工具 - 高级CLI",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
使用示例:
  # 验证单个包
  python advanced_cli.py single numpy
  
  # 验证单个包（指定版本）
  python advanced_cli.py single torch --version 1.12.0
  
  # 批量验证（使用默认配置）
  python advanced_cli.py batch packages_config.json
  
  # 批量验证（指定包）
  python advanced_cli.py batch packages_config.json --filter numpy pandas torch
  
  # 批量验证（并行模式，实验性）
  python advanced_cli.py batch packages_config.json --parallel
  
  # 列出配置文件中的包
  python advanced_cli.py list packages_config.json
  
  # 生成文本验证报告
  python advanced_cli.py report
  
  # 生成HTML验证报告
  python advanced_cli.py report --format html
        """
    )
    
    subparsers = parser.add_subparsers(dest='command', help='可用命令')
    
    # 单包验证命令
    single_parser = subparsers.add_parser('single', help='验证单个包')
    single_parser.add_argument('package', help='包名')
    single_parser.add_argument('--version', help='指定版本')
    single_parser.add_argument('--tests', help='自定义测试文件路径')
    
    # 批量验证命令
    batch_parser = subparsers.add_parser('batch', help='批量验证')
    batch_parser.add_argument('config', help='配置文件路径')
    batch_parser.add_argument('--filter', nargs='+', help='筛选要验证的包')
    batch_parser.add_argument('--parallel', action='store_true', help='并行执行（实验性）')
    
    # 列表命令
    list_parser = subparsers.add_parser('list', help='列出配置文件中的包')
    list_parser.add_argument('config', help='配置文件路径')
    
    # 报告命令
    report_parser = subparsers.add_parser('report', help='生成验证报告')
    report_parser.add_argument('--log-dir', default='validation_logs', help='日志目录')
    report_parser.add_argument('--format', choices=['text', 'html'], default='text', help='报告格式')
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return
    
    cli = AdvancedCLI()
    
    try:
        if args.command == 'single':
            result = cli.validate_single_package(
                args.package, 
                args.version, 
                args.tests
            )
            
            # 输出结果摘要
            print(f"\n📊 验证结果:")
            print(f"包名: {result.get('package')}")
            print(f"版本: {result.get('package_info', {}).get('version', 'Unknown')}")
            print(f"整体状态: {'✅ 成功' if result.get('overall_success') else '❌ 失败'}")
            
            # 显示测试结果
            tests = result.get('tests', [])
            if tests:
                print(f"测试结果:")
                for test in tests:
                    test_name = test.get('test_name', test.get('test_type', 'Unknown'))
                    status = '✅' if test.get('success') else '❌'
                    print(f"  {status} {test_name}")
            
        elif args.command == 'batch':
            result = cli.validate_batch(args.config, args.filter, args.parallel)
            cli._print_detailed_report(result)
            
        elif args.command == 'list':
            cli.list_packages(args.config)
            
        elif args.command == 'report':
            cli.generate_report(args.log_dir, args.format)
            
    except KeyboardInterrupt:
        print(f"\n❌ 用户取消操作")
        sys.exit(1)
    except Exception as e:
        print(f"❌ 执行错误: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()